package org.xin.security.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xin.common.util.XinUtil;
import org.xin.framework.constant.PermissionType;
import org.xin.security.pojo.bo.UserInfo;
import org.xin.security.pojo.entity.SysMenuSecurity;
import org.xin.security.pojo.entity.SysRole;
import org.xin.security.pojo.entity.SysRolePermission;
import org.xin.security.service.ISysMenuSecurityService;
import org.xin.security.service.ISysMenuService;
import org.xin.security.service.ISysRolePermissionService;
import org.xin.security.service.ISysRoleService;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p> 用户权限处理 </p>
 * @modified By：$
 * @version: $
 */
@Component
public class PermissionMangerComponent {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysRolePermissionService rolePermissionService;

    @Autowired
    private ISysMenuSecurityService menuSecurityService;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(UserInfo user) {
        Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
            return roles;
        }

        return rolePermissionService.selectPermissionByRoleId(roles, user.getSysRoleId(), PermissionType.DATA.ordinal());
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(UserInfo user) {
        Set<String> perms = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
            return perms;
        }
        return rolePermissionService.selectPermissionByRoleId(perms, user.getSysRoleId(), PermissionType.MENU.ordinal());
    }
}
